package com.xgy.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgy.backend.dto.BoardKifuDto;
import com.xgy.backend.domain.Level0Board;
import com.xgy.backend.dto.ScreeningConditionDto;
import com.xgy.backend.service.AsyncService;
import com.xgy.backend.service.Level0BoardService;
import com.xgy.backend.mapper.Level0BoardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
* @author golaxy
* @description 针对表【level0_board】的数据库操作Service实现
* @createDate 2023-09-12 11:51:37
*/
@Service
public class Level0BoardServiceImpl extends ServiceImpl<Level0BoardMapper, Level0Board>
    implements Level0BoardService{
    @Autowired
    Level0BoardMapper level0BoardMapper;

    @Autowired
    AsyncService asyncService;

    @Value("${async.executor.thread.batchSize}")
    private int batchSize;

    @Override
    public List<BoardKifuDto> getScreeningResult(ScreeningConditionDto screeningCondition) {
        List<BoardKifuDto> res = new ArrayList<>();
        long totalCount = level0BoardMapper.selectCount(new QueryWrapper<>());

        //多线程批次查询数据库
        List<CompletableFuture<List<BoardKifuDto>>> tasks = new ArrayList<>();
        for (int i = 0; i < Math.ceil(totalCount * 1.0 / batchSize); i++) {
            tasks.add(asyncService.executeBoardAsync(screeningCondition, i * batchSize, ((i + 1) * batchSize)-1));
        }

        //使用 CompletableFuture.allOf 来等待所有任务完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(
                tasks.toArray(new CompletableFuture[0])
        );

        //当所有任务完成后，执行合并结果的操作
        CompletableFuture<List<BoardKifuDto>> combinedFuture = allOf.thenApply(v ->
                tasks.stream()
                        .map(CompletableFuture::join) // 等待每个任务完成并获取结果
                        .flatMap(List::stream) // 将每个任务的结果合并成一个流
                        .collect(Collectors.toList()) // 将流转换为列表
        );

        try {
            res = combinedFuture.get(); // 获取最终合并的结果
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        return res;
    }

}




